/*
package org.example.util;

import com.fazecast.jSerialComm.SerialPort;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class SerialPortUtil {

    public void executeWithPort(SerialPort serialPort, PrinterAction action) {
        if (!serialPort.openPort()) {
            log.error("无法打开串口: {}", serialPort.getSystemPortName());
            throw new PrinterException("打印机连接失败");
        }

        try (OutputStream outputStream = serialPort.getOutputStream()) {
            action.execute(outputStream);
        } catch (Exception e) {
            log.error("打印操作异常", e);
            throw new PrinterException("打印失败: " + e.getMessage());
        } finally {
            serialPort.closePort();
        }
    }

    @FunctionalInterface
    public interface PrinterAction {
        void execute(OutputStream outputStream) throws Exception;
    }

    public static class PrinterException extends RuntimeException {
        public PrinterException(String message) {
            super(message);
        }
    }



    public static void main(String[] args) {
        try {
            // 获取所有打印机服务
            PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
            PrintService printer = null;
            for (PrintService printService : printServices) {
                if (printService.getName().equals("HPRT N31C")) {  // 替换为实际打印机名称
                    printer = printService;
                    break;
                }
            }

            if (printer != null) {
                // 创建打印任务
                DocPrintJob job = printer.createPrintJob();

                job.addPrintJobListener(new PrintJobAdapter() {
                    @Override
                    public void printJobFailed(PrintJobEvent pje) {
                        System.err.println("打印任务失败: " + pje.getPrintEventType());
                    }

                    @Override
                    public void printJobCompleted(PrintJobEvent pje) {
                        System.out.println("打印任务完成");
                    }

                    @Override
                    public void printJobCanceled(PrintJobEvent pje) {
                        System.out.println("打印任务取消");
                    }
                });

                // ESC/POS命令：开始打印
                */
/*byte[] escPosCommands = new byte[]{
                        0x1B, 0x40,  // 初始化打印机 (ESC @)
                        0x1B, 0x45, 0x01, // 加粗模式开 (ESC E 1)
                        0x1B, 0x61, 0x01, // 居中对齐 (ESC a 1)
                        0x1B, 0x47, 0x01, // 加大字体
                        0x1B, 0x21, 0x30, // 选择字体大小 (ESC ! 0x30)
                        'T', 'E', 'S', 'T', ' ', 'P', 'R', 'I', 'N', 'T', ' ', 'C', 'O', 'M', 'P', 'L', 'E', 'T', 'E', 0x0D, // 打印内容
                        0x1B, 0x45, 0x00, // 关闭加粗模式 (ESC E 0)
                        0x1B, 0x64, 0x02  // 打印并走纸 (ESC d 2)
                };*//*


                // 4. 构建 ESC/POS 命令（改进版）
                StringBuilder tspl
                        = new StringBuilder();

                tspl.append("SIZE 131 mm, 72 mm\r\n");
                tspl.append("GAP 2 mm, 0 mm\r\n");
                tspl.append("DIRECTION 0,0\r\n");
                tspl.append("REFERENCE 0,0\r\n");
                tspl.append("OFFSET 0 mm\r\n");
                tspl.append("SET PEEL OFF\r\n");
                tspl.append("SET CUTTER OFF\r\n");
                tspl.append("SET PARTIAL_CUTTER OFF\r\n");
                tspl.append("CLS\r\n");
                tspl.append("TEXT 100,100,\"TSS24.BF2\",0,1,1,\"Hello, USB TSPL!\"\r\n");
                tspl.append("BARCODE 100,150,\"128\",100,1,0,2,2,\"ABC123456\"\r\n");
                tspl.append("PRINT 1\r\n");


                byte[] tsplCommands = new byte[]{
                        0x1B, 0x40, // 初始化打印机 (ESC @)
                        0x1D, 0x61, 0x01, // 居中对齐 (GS a 1)
                        0x1B, 0x4C, 0x00, 0x00, 0x50, 0x00, // 设置标签宽度和高度 (131mm x 72mm)
                        0x1B, 0x33, 0x03, // 设置打印密度 (203 dpi)
                        0x1B, 0x4D, 0x00, // 设置打印模式
                        0x1B, 0x50, 0x01, // 打印开始
                        0x1B, 0x54, 'T', 'E', 'S', 'T', ' ', 'P', 'R', 'I', 'N', 'T', 0x0A, // 打印文本内容
                        0x1B, 0x64, 0x02, // 打印并走纸
                        0x1B, 0x4D, 0x00  // 结束命令
                };

                // 转换为字节数组（使用GBK编码处理中文）
                byte[] escPosCommands = tspl.toString().getBytes("GBK");

                String tsplCommand = buildTSPLCommand();
                byte[] printData = tsplCommand.getBytes(StandardCharsets.ISO_8859_1);

                // 创建自定义介质尺寸属性
                MediaPrintableArea customSize = new MediaPrintableArea(
                        0, 0, 72, 131, MediaPrintableArea.MM
                );
                // 设置打印属性
                PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
                attributes.add(new Copies(1));
                attributes.add(customSize);


                // 将命令转换为 Doc 对象
                Doc doc = new SimpleDoc(tsplCommands, DocFlavor.BYTE_ARRAY.AUTOSENSE, null);

                // 执行打印任务
                job.print(doc, attributes);
                System.out.println("ESC/POS 打印任务已提交");
            } else {
                System.out.println("未找到指定的打印机");
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("打印失败: " + e.getMessage());
        }
    }


    private static String buildTSPLCommand() {
        StringBuilder cmd = new StringBuilder();

        // 基本设置
        cmd.append("SIZE 80 mm,40 mm\n")      // 标签尺寸 (宽,高)
                .append("GAP 2 mm,0 mm\n")         // 标签间隙
                .append("DIRECTION 1\n")           // 打印方向 (0,1)
                .append("REFERENCE 0,0\n")         // 参考点
                .append("CLS\n");                  // 清除缓冲区

        // 添加文本内容
        cmd.append("TEXT 50,50,\"TSS24.BF2\",0,1,1,\"订单号: 20230721001\"\n")
                .append("TEXT 50,100,\"TSS24.BF2\",0,1,1,\"产品: 测试商品\"\n")
                .append("TEXT 50,150,\"TSS24.BF2\",0,1,1,\"数量: 5\"\n");

        // 添加条码 (Code 128)
        cmd.append("BARCODE 50,200,\"128\",80,1,0,2,2,\"123456789\"\n");

        // 添加矩形框
        cmd.append("BOX 20,20,300,250,2\n");

        // 打印指令
        cmd.append("PRINT 1\n"); // 打印1份

        return cmd.toString();
    }
}*/
